/* eslint-disable no-unused-vars */
/* eslint-disable jsx-a11y/alt-text */
/* eslint-disable import/first */
/* global window */
/* global document */
import React, { PureComponent, Fragment } from 'react'
import PropTypes from 'prop-types'
import { withRouter } from 'umi'
import { connect } from 'umi'
import { MyLayout } from 'components'
import {
  BackTop,
  Layout,
  Form,
  Drawer,
  message,
  Alert,
  Avatar,
  Menu,
  Modal,
  Input,
  Button,
} from 'antd'
import { enquireScreen, unenquireScreen } from 'enquire-js'
const { pathToRegexp } = require('path-to-regexp')
import { post } from '@/services/https'
import { config, getLocale } from 'utils'
import Error from '../pages/404'
import styles from './PrimaryLayout.less'
import { DownOutlined, UpOutlined } from '@ant-design/icons'
import { USERPWD } from '@/utils/regExp'
import store from 'store'
import { concatArray } from 'echarts-gl'
import { Trans, withI18n } from '@lingui/react'
const { SubMenu } = Menu
const { Content } = Layout
const { Header, Bread, Sider } = MyLayout
const layout = {
  labelCol: {
    span: 4,
  },
  wrapperCol: {
    span: 20,
  },
}
const tailLayout = {
  wrapperCol: {
    offset: 4,
    span: 20,
  },
}
@withRouter
@connect(({ app, loading }) => ({ app, loading }))
class PrimaryLayout extends PureComponent {
  state = {
    isMobile: false,
    enddate: '',
    ifexpire: 0,
    allnum: 0,
    usenum: 0,
    is_pwd_expires: 0,
    isModal: false,
    expire_remind: 0,
    remind_days: 0,
    initialValues: {},
    key: 0,
    keyes: 0,
    loginName: sessionStorage.getItem('loginName'),
    arr: 1,
  }
  formRef = React.createRef()
  componentDidMount() {
    if (sessionStorage.getItem('is_pwd_expires') == 1) {
      this.setState({ isModal: true })
    } else {
      this.setState({ isModal: false })
    }
    this.enquireHandler = enquireScreen((mobile) => {
      const { isMobile } = this.state
      if (isMobile !== mobile) {
        this.setState({
          isMobile: mobile,
        })
      }
    })
    const { dispatch } = this.props
    // var n = 30000;  //时间设置(20分钟)
    var n = 300000 //时间设置(5分钟)
    if (sessionStorage.getItem('login_timeout') != null) {
      n = sessionStorage.getItem('login_timeout')
    } else {
      n = 300000
    }
  }
  componentWillUnmount() {
    unenquireScreen(this.enquireHandler)
  }
  onCollapseChange = (collapsed) => {
    this.props.dispatch({
      type: 'app/handleCollapseChange',
      payload: collapsed,
    })
  }
  onFinish = (values) => {
    const { location, i18n } = this.props
    values.username = sessionStorage.getItem('loginName')
    delete values.confirm
    const { dispatch } = this.props
    post('action?command=changepasswd', values).then((res) => {
      if (res.succ) {
        message.success('修改成功，请用新密码重新登录')
        dispatch({ type: 'app/signOut' })
        this.props.onSignOut()
      } else {
        message.error(res.error)
      }
    })
    this.formRef.current.resetFields()
    this.setState({ isModal: true })
  }
  handleClickMenu = (e) => {
    const { dispatch } = this.props
    dispatch({ type: 'app/signOut' })
    this.props.onSignOut()
  }
  handleCancel = () => {
    this.setState({ isModal: false })
  }
  Lide = (key) => {
    this.setState({ arr: key })
    if (key === 1) {
      //我的课堂
      this.props.history.push('/Myclassroom')
    } else if (key === 2) {
      //课堂检测
      this.props.history.push('/ClassroomTest')
    } else if (key === 3) {
      //我的作业
      this.props.history.push('/Myhomework')
    } else if (key === 4) {
      //我的作品
      this.props.history.push('/Myworks')
    } else if (key === 5) {
      //展示作品
      this.props.history.push('/DisplayWorks')
    } else if (key === 6) {
      //编程工具
      this.props.history.push('/programming')
    } else if (key === 7) {
      //班级资源
      this.props.history.push('/ClassResources')
    }
  }
  showModal = () => {
    this.setState({ isModal: true })
  }
  render() {
    const { app, location, children } = this.props
    const { theme, collapsed, notifications } = app
    const user = JSON.parse(sessionStorage.getItem('user')) || {}
    const permissions = JSON.parse(sessionStorage.getItem('permissions')) || {}
    const routeList = JSON.parse(sessionStorage.getItem('routeList')) || []
    const { isMobile, isModal, key, keyes, loginName, arr } = this.state
    const { onCollapseChange } = this
    // Localized route name.
    let asasdad = true
    if (app.locationPathname === '/programming/0') {
      asasdad = false
    } else {
      asasdad = true
    }
    if (app.locationPathname === '/Myclassroom') {
      this.setState({ arr: 1 })
    } else if (app.locationPathname === '/ClassroomTest') {
      this.setState({ arr: 2 })
    } else if (app.locationPathname === '/Myhomework') {
      this.setState({ arr: 3 })
    } else if (app.locationPathname === '/Myworks') {
      this.setState({ arr: 4 })
    } else if (app.locationPathname === '/DisplayWorks') {
      this.setState({ arr: 5 })
    } else if (app.locationPathname === '/programming') {
      this.setState({ arr: 6 })
    } else if (app.locationPathname === '/ClassResources') {
      this.setState({ arr: 7 })
    }
    const lang = getLocale()
    const newRouteList =
      lang !== 'en'
        ? routeList.map((item) => {
            const { name, ...other } = item
            return {
              ...other,
              name: (item[lang] || {}).name || name,
            }
          })
        : routeList

    // Find a route that matches the pathname.
    const currentRoute = newRouteList.find(
      (_) => _.route && pathToRegexp(_.route).exec(location.pathname)
    )

    // Query whether you have permission to enter this page
    const hasPermission = currentRoute
      ? permissions.visit.includes(currentRoute.id)
      : false
    // MenuParentId is equal to -1 is not a available menu.
    const menus = newRouteList.filter((_) => _.menuParentId !== '-1')

    return (
      <div ref={(e) => (this.divDom = e)}>
        <Fragment>
          <Layout
            style={{
              overflow: 'hidden',
              minWidth: '1500px',
              background: '#fff',
            }}
          >
            <div
              style={{
                display: 'flex',
                justifyContent: 'flex-start',
                width: '100%',
              }}
            >
              <div style={{ width: '100%' }} className={styles.Zbj}>
                <div className={styles.container} id="primaryLayout">
                  {/* <Header {...headerProps} /> */}
                  {asasdad ? (
                    <div className="Top_yu">
                      <div style={{ display: 'flex', alignItems: 'center' }}>
                        <div style={{ marginRight: '15px' }}>
                          <img
                            style={{
                              width: '70px',
                              height: '70px',
                              borderRadius: '45px',
                            }}
                            alt=""
                            src={require('../imges/25.png')}
                          />
                        </div>
                        <div>
                          <div className={styles.LOGnAME}>{loginName}</div>
                          {/* <div className={styles.LOGnAME1} onClick={this.handleClickMenu}>
                                                        
                                                    </div> */}
                          <Menu
                            key="user"
                            mode="horizontal"
                            style={{
                              background: 'none',
                              border: 'none',
                              lineHeight: '22px',
                            }}
                          >
                            <SubMenu
                              className={styles.LOGnAME1}
                              title={
                                <Fragment>
                                  <span
                                    style={{ color: '#fff', marginRight: 4 }}
                                  >
                                    <Trans>设置</Trans>
                                  </span>
                                </Fragment>
                              }
                            >
                              <Menu.Item onClick={this.showModal}>
                                <Trans>Xg</Trans>
                              </Menu.Item>
                              <Menu.Item
                                key="SignOut"
                                onClick={this.handleClickMenu}
                              >
                                <Trans>Sign out</Trans>
                              </Menu.Item>
                            </SubMenu>
                          </Menu>
                        </div>
                      </div>
                      <div
                        style={{
                          display: 'flex',
                          alignItems: 'center',
                          flexDirection: 'row',
                          color: '#fff',
                        }}
                      >
                        <div
                          className={arr === 1 ? 'bih' : ''}
                          onClick={() => this.Lide(1)}
                          style={{
                            width: '104px',
                            paddingTop: '13px',
                            height: '104px',
                            cursor: 'pointer',
                            textAlign: 'center',
                          }}
                        >
                          <div>
                            <img
                              style={{
                                width: '60px',
                              }}
                              alt=""
                              src={require('../imges/ketang.png')}
                            />
                          </div>
                          <div>我的课堂</div>
                        </div>
                        <div
                          className={arr === 2 ? 'bih' : ''}
                          onClick={() => this.Lide(2)}
                          style={{
                            width: '104px',
                            paddingTop: '13px',
                            height: '104px',
                            cursor: 'pointer',
                            textAlign: 'center',
                          }}
                        >
                          <div>
                            <img
                              style={{
                                width: '60px',
                              }}
                              alt=""
                              src={require('../imges/ceyan.png')}
                            />
                          </div>
                          <div>课堂测试</div>
                        </div>
                        <div
                          className={arr === 3 ? 'bih' : ''}
                          onClick={() => this.Lide(3)}
                          style={{
                            width: '104px',
                            paddingTop: '13px',
                            height: '104px',
                            cursor: 'pointer',
                            textAlign: 'center',
                          }}
                        >
                          <div>
                            <img
                              style={{
                                width: '60px',
                              }}
                              alt=""
                              src={require('../imges/zuoye.png')}
                            />
                          </div>
                          <div>我的作业</div>
                        </div>
                        <div
                          className={arr === 4 ? 'bih' : ''}
                          onClick={() => this.Lide(4)}
                          style={{
                            width: '104px',
                            paddingTop: '13px',
                            height: '104px',
                            cursor: 'pointer',
                            textAlign: 'center',
                          }}
                        >
                          <div>
                            <img
                              style={{
                                width: '60px',
                              }}
                              alt=""
                              src={require('../imges/zuopin.png')}
                            />
                          </div>
                          <div>我的作品</div>
                        </div>
                        <div
                          className={arr === 5 ? 'bih' : ''}
                          onClick={() => this.Lide(5)}
                          style={{
                            width: '104px',
                            paddingTop: '13px',
                            height: '104px',
                            cursor: 'pointer',
                            textAlign: 'center',
                          }}
                        >
                          <div>
                            <img
                              style={{
                                width: '60px',
                              }}
                              alt=""
                              src={require('../imges/zhanshi.png')}
                            />
                          </div>
                          <div>展示作品</div>
                        </div>
                        <div
                          className={arr === 6 ? 'bih' : ''}
                          onClick={() => this.Lide(6)}
                          style={{
                            width: '104px',
                            paddingTop: '13px',
                            height: '104px',
                            cursor: 'pointer',
                            textAlign: 'center',
                          }}
                        >
                          <div>
                            <img
                              style={{
                                width: '60px',
                              }}
                              alt=""
                              src={require('../imges/bianc.png')}
                            />
                          </div>
                          <div>编程工具</div>
                        </div>
                        <div
                          className={arr === 7 ? 'bih' : ''}
                          onClick={() => this.Lide(7)}
                          style={{
                            width: '104px',
                            paddingTop: '13px',
                            height: '104px',
                            cursor: 'pointer',
                            textAlign: 'center',
                          }}
                        >
                          <div>
                            <img
                              style={{
                                width: '60px',
                              }}
                              alt=""
                              src={require('../imges/banji.png')}
                            />
                          </div>
                          <div>班级资源</div>
                        </div>
                      </div>
                    </div>
                  ) : (
                    ''
                  )}

                  <Content className={styles.content} style={{ height: '85%' }}>
                    {hasPermission ? children : <Error />}
                  </Content>
                  {/* <BackTop
                                        className={styles.backTop}
                                        target={() => document.querySelector('#primaryLayout')}
                                    /> */}
                </div>
              </div>
            </div>
          </Layout>
        </Fragment>
        <Modal
          title="修改密码"
          visible={isModal}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          maskClosable={false}
          footer={null}
        >
          <Form {...layout} name="basic" initialValues onFinish={this.onFinish}>
            <Form.Item
              label="旧密码"
              name="password"
              rules={[
                {
                  required: true,
                },
              ]}
            >
              <Input.Password visibilityToggle={false} />
            </Form.Item>
            <Form.Item
              extra="包括至少1个大写字母，1个小写字母，1个数字，1个特殊字符，长度8-32"
              label="新密码"
              name="newpasswd"
              rules={[
                {
                  required: true,
                },
                {
                  pattern: USERPWD,
                  message:
                    '包括至少1个大写字母，1个小写字母，1个数字，1个特殊字符，长度8-32',
                },
              ]}
            >
              <Input.Password visibilityToggle={false} />
            </Form.Item>
            <Form.Item
              extra="包括至少1个大写字母，1个小写字母，1个数字，1个特殊字符，长度8-32"
              name="confirm"
              label="确认密码"
              dependencies={['newpasswd']}
              hasFeedback
              rules={[
                {
                  required: true,
                  message: '请输入密码!',
                },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('newpasswd') === value) {
                      return Promise.resolve()
                    }

                    return Promise.reject(
                      new Error('密码输入不一致，重新输入!')
                    )
                  },
                }),
              ]}
            >
              <Input.Password visibilityToggle={false} />
            </Form.Item>
            <Form.Item {...tailLayout}>
              <Button type="primary" htmlType="submit">
                确定修改
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    )
  }
}

PrimaryLayout.propTypes = {
  children: PropTypes.element.isRequired,
  location: PropTypes.object,
  dispatch: PropTypes.func,
  app: PropTypes.object,
  loading: PropTypes.object,
}

export default PrimaryLayout
